package security.Session;

import java.util.*;
import security.Roles.*;

public class Session {
	
	private String sessionId;
	
	private User currentUser;
	
	// in principe alleen privileges nodig
	private Vector<Role> userRoles = new Vector<Role>();
	private Vector<Group> userGroups = new Vector<Group>();
	private Vector<Privilege> userPrivileges = new Vector<Privilege>();
	
	private boolean isLoggedIn;
	
	public Session() {
		// session ID aanmaken
		UUID id = UUID.randomUUID();
		setSessionId(id.toString());	
		this.isLoggedIn = false;	
		
	}
	

	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}


	public User getCurrentUser() {
		return currentUser;
	}


	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}


	public Vector<Group> getUserGroups() {
		return userGroups;
	}

	public void addUserGroup(Group group) {
		this.userGroups.add(group);		
	}
	


	public void setUserGroups(Vector<Group> userGroups) {
		this.userGroups = userGroups;
	}


	public Vector<Privilege> getUserPrivileges() {
		return userPrivileges;
	}


	public void setUserPrivileges(Vector<Privilege> userPrivileges) {
		this.userPrivileges = userPrivileges;
	}

	public void addUserPrivilege(Privilege userPrivilege) {
		this.userPrivileges.add(userPrivilege);
	}

	public Vector<Role> getUserRoles() {
		return userRoles;
	}


	public void setUserRoles(Vector<Role> userRoles) {
		this.userRoles = userRoles;
	}

	public void addUserRole(Role userRole) {
		this.userRoles.add(userRole);
	}


	public boolean isLoggedIn() {
		return isLoggedIn;
	}


	public void setLoggedIn(boolean isLoggedIn) {
		this.isLoggedIn = isLoggedIn;
		
		if(this.isLoggedIn) {
			// user has logged in, get privilges, groups, roles, etc
			// this assumes that the user is set in this session before
			// setLoggedIn is called
			if (this.getCurrentUser() == null) {
				throw new RuntimeException("Call setCurrentUser before setLoggedIn");
			}
			// get groups			
			userGroups.addAll(this.getCurrentUser().getUserGroups());
			userPrivileges.addAll(this.getCurrentUser().getUserPrivilege());
			userRoles.addAll(this.getCurrentUser().getUserRoles());
			
			// add all privileges of this user from the groups he's in
			for (int i=0;i<this.userGroups.size();i++){
				for (int j=0;j<userGroups.get(i).getGroupPrivileges().size();j++) {
					if (! userPrivileges.contains(userGroups.get(i).getGroupPrivileges().get(j))) {
						userPrivileges.add(userGroups.get(i).getGroupPrivileges().get(j));
					}
				}
			}
			
		}
	}
	
	
	
}
